package com.ch02xml.controller;

import com.ch02xml.pojo.UserInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.UUID;

@Controller
public class Testcontroller {

    @RequestMapping("/test")
    public String test(Model model){
        UserInfo userInfo = new UserInfo();
userInfo.setUsername("好想睡觉");
model.addAttribute("user",userInfo);
        return "us";
    }



    @PostMapping("/upload")
    public String upload(Model model, MultipartFile fileName, HttpServletRequest request){
        if(!fileName.isEmpty()) {
            String replace = UUID.randomUUID().toString().replace("-", "");
            String originalFilename = fileName.getOriginalFilename();

            String realPath = request.getServletContext().getRealPath("/upImg");

            String name = replace + originalFilename;
            File file = new File(realPath);
            if (!file.exists()) {
                file.mkdirs();
            }
            try {
                fileName.transferTo(new File(realPath+"/", name));
            } catch (Exception e) {
                e.printStackTrace();
                model.addAttribute("msg","文件上传失败");
            }
            model.addAttribute("upImg", name);
            System.out.println(name);

            return "upload";
        }else{
            model.addAttribute("msg","文件必填");
            return "index";
        }
    }

}
